package controllers

import "myerp/models"
import "time"

type DepotController struct {
	CommonController
}

//添加仓库
func (c *DepotController) Add() {
	if c.Ctx.Request.Method == "POST" {
		reData := make(map[string]interface{})
		reData["status"] = 1
		var md models.Depot
		md.Name = c.GetString("name")
		md.Uid = int(UserInfo.Id)
		md.Ctime = int(time.Now().Unix())
		_, err := models.AddDepot(&md)
		if err != nil {
			reData["msg"] = "添加仓库失败！"
		} else {
			reData["url"] = "/depot/list"
			reData["status"] = 1
		}
		c.Data["json"] = reData
		c.ServeJSON()
	}
	c.Data["ActionName"] = "添加仓库"
	c.Layout = "base.html"
	c.TplName = "depot/add.html"
}

//列表仓库
func (c *DepotController) List() {
	pid, _ := c.GetInt("pid", 0)
	l, _ := models.GetAllDepotNotPage()
	c.Data["ActionName"] = "仓库列表"
	c.Data["ol"] = l
	c.Data["pid"] = pid
	c.Layout = "base.html"
	c.TplName = "depot/list.html"

}

//编辑仓库
func (c *DepotController) Edite() {
	var id int
	if c.Ctx.Request.Method == "POST" {
		reData := make(map[string]interface{})
		reData["status"] = 0
		var md models.Depot
		id, err := c.GetInt("id")
		if err != nil {
			reData["msg"] = "修改的分类不存在！"
			c.Data["json"] = reData
			c.ServeJSON()
			return
		}
		md.Id = id
		md.Name = c.GetString("name")
		md.Uid = int(UserInfo.Id)
		err = models.UpdateDepotById(&md)
		if err != nil {
			reData["msg"] = "修改分类失败"
		} else {
			reData["status"] = 1
			reData["url"] = "/depot/list"
		}
		c.Data["json"] = reData
		c.ServeJSON()
		return
	}

	id, err := c.GetInt("id")
	if err != nil {
		c.Redirect("/depot/list", 302)
		return
	}
	sd, err := models.GetDepotById(id)
	if err != nil {
		c.Redirect("/depot/list", 302)
		return
	}
	c.Data["Sdata"] = sd
	c.Layout = "base.html"
	c.TplName = "depot/edite.html"

}

//删除仓库
func (c *DepotController) Delete() {
	var id int
	reData := make(map[string]interface{})
	reData["status"] = 0
	id, err := c.GetInt("id")
	if err != nil || id < 1 {
		reData["msg"] = "删除的仓库不存在!"
		c.ServeJSON()
		return
	}
	err = models.DeleteDepot(id)
	if err != nil {
		reData["msg"] = "删除失败!"
		c.ServeJSON()
		return
	}
	reData["status"] = 1
	reData["msg"] = "删除成功!"
	c.Data["json"] = reData
	c.ServeJSON()
	return
}
